#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMediaDevices>
#include <QAudioDevice>
#include <QDebug>
#include <QDataStream>

using namespace std;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    QAudioFormat AudioFormat;
    qDebug("Enter main()");

    AudioFormat.setSampleRate(44100);
    AudioFormat.setChannelCount(2);
    AudioFormat.setSampleFormat(QAudioFormat::Int16);

    AudioFile *audioFile = new AudioFile(AudioFormat);

    audioSource = new QAudioSource(QMediaDevices::defaultAudioInput(), AudioFormat);
    audioSource->start(audioFile);

    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    audioSource->stop();

    delete ui;
}

/******************************** Audio file **********************************/

AudioFile::AudioFile(const QAudioFormat &format)
    : m_format(format)
{
    open(QIODevice::WriteOnly);
    start();
}

void AudioFile::start()
{
    file.setFileName("test.pcm");
    file.open(QIODevice::WriteOnly | QIODevice::Truncate);
    qDebug("open file: out.pcm");
}

void AudioFile::stop()
{
    close();
    file.close();
    qDebug("close file: out.pcm");
}

qint64 AudioFile::readData(char * /* data */, qint64 /* maxlen */)
{
    qDebug("readData ");
    return 0;
}

qint64 AudioFile::writeData(const char *data, qint64 len)
{
    file.write(data, len);
    qDebug(". ");

    total += len;
    if (total > 1 * 1024 * 1024) {
        file.close();
        qDebug("close file: out.pcm");
        /**
         * TODO: 到达指定录取长度后通知MainWindow去delete audioSource，
         * 或者屏蔽这里的file close代码，靠关闭主窗口来实现保存录制的文件
         */
    }

    return len;
}
